package com.uphone.kingmall.activity.personal;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.uphone.kingmall.activity.personal.set.AgreementActivity;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.BuyVipPriceBean;
import com.uphone.kingmall.bean.PayAliCallbackBean;
import com.uphone.kingmall.bean.PayResult;
import com.uphone.kingmall.bean.PayWxCallbackBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.AppUtil;
import com.uphone.kingmall.utils.DialogUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.view.dialog.RadishDialog;
import com.uphone.kingmall.wxapi.WXPayEntryActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VipUpgradeActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.linear_title)
    LinearLayout linearTitle;
    @BindView(R.id.rb_ali)
    RadioButton rbAli;
    @BindView(R.id.rb_wchat)
    RadioButton rbWchat;
    @BindView(R.id.rb_wallet)
    RadioButton rbWallet;
    @BindView(R.id.rg_pay)
    RadioGroup rgPay;
    @BindView(R.id.cb_agree)
    CheckBox cbAgree;
    @BindView(R.id.tv_privacy)
    TextView tvPrivacy;
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    @BindView(R.id.tv_pay)
    TextView tvPay;

    private RadishDialog dialog;
    private double money = 0.0;

    private int type;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_vip_upgrade;
    }

    @Override
    public void initView() {
        mImmersionBar
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.status_bar)
                .navigationBarColor(R.color.black)
                .fullScreen(false)
                .init();
    }

    @Override
    public void initData() {
        type = getIntent().getIntExtra("type", 0);
        OkGoUtils.normalRequestGet(MyUrl.GetVipPrices, new onNormalRequestListener() {
            @Override
            public void onSuccess(String json, int code) {
                if (code == 0) {
                    BuyVipPriceBean bean = GsonUtils.getGson().fromJson(json, BuyVipPriceBean.class);
                    if (type == 0) {
                        money = Math.abs(sub(bean.getData().get(0).getDiscountPrice(), bean.getData().get(1).getDiscountPrice()));
                    } else {
                        money = bean.getData().get(1).getDiscountPrice();
                    }
                    tvAllMoney.setText(money + "");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    /**
     * 提供精确的减法运算。
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private void wxPay(final String body) {
        AppUtil.checkWchat(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayWxCallbackBean bean = GsonUtils.getGson().fromJson(body, PayWxCallbackBean.class);
                PayWxCallbackBean.SignBean sign = bean.getSign();
                PayReq request = new PayReq();
                request.appId = sign.getAppId();
                request.partnerId = sign.getPartnerId();
                request.prepayId = sign.getPrepayId();
                request.packageValue = sign.getPackageValue();
                request.nonceStr = sign.getNonceStr();
                request.timeStamp = sign.getTimeStamp();
                request.sign = sign.getSign();
                WXPayEntryActivity.activity = VipUpgradeActivity.this;
                MyApplication.api.sendReq(request);
            }
        });

    }

    @Override
    public void wxPaySuccess() {
        super.wxPaySuccess();
        paySuccess();
    }

    private void alipay(final String body) {
        AppUtil.checkAli(this, new AppUtil.AppCheckCallback() {
            @Override
            public void callBack() {
                PayAliCallbackBean bean = GsonUtils.getGson().fromJson(body, PayAliCallbackBean.class);
                final String sign = bean.getSign();
                // 必须异步调用
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(VipUpgradeActivity.this);
                        final Map<String, String> resultMap = alipay.payV2(sign, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                PayResult result = new PayResult(resultMap);
                                String resultStatus = result.getResultStatus();
                                if (TextUtils.equals(resultStatus, "9000")) {
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付成功");
                                    paySuccess();
                                } else if (TextUtils.equals(resultStatus, "6001")) {
                                    com.blankj.utilcode.util.ToastUtils.showShort("支付取消");
                                } else {
                                    com.blankj.utilcode.util.ToastUtils.showShort(resultStatus);
                                }
                            }
                        });
                    }
                }).start();
            }
        });

    }

    private void paySuccess() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        ToastUtils.showShortToast(VipUpgradeActivity.this, "支付成功");
        ActivityCollector.removeAll(MainActivity.class);
        openActivity(ShangJiaRuZhuActivity.class);

    }

    @Override
    public void onPayPsdSuccess(String passWord) {
        super.onPayPsdSuccess(passWord);
        //密码成功
    }

    @OnClick({R.id.iv_back, R.id.tv_pay, R.id.tv_privacy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_privacy:
                openActivity(AgreementActivity.class);
                break;
            case R.id.tv_pay:
                if (!cbAgree.isChecked()) {
                    ToastUtils.showShortToast(this, "请先同意支付协议！");
                    return;
                }
                if (rgPay.getCheckedRadioButtonId() == R.id.rb_wallet) {
                    //钱包支付
                    dialog = DialogUtil.showDialogWalletPay(VipUpgradeActivity.this, new DialogUtil.OnWalletPayDialogCallBack() {
                        @Override
                        public void callBack(RadishDialog dialog, View view, String psd) {
                            PayVip(psd);
                        }
                    });
                } else {
                    PayVip("");
                }
                break;
        }
    }

    private void PayVip(String pass) {
        HttpParams params = new HttpParams();
        params.put("type", 5);
        params.put("payType", rgPay.getCheckedRadioButtonId() == R.id.rb_ali ? 1 : (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat ? 2 : 3));
        if (!TextUtils.isEmpty(pass)) {
            params.put("paypass", pass);
        }
        params.put("money", money + "");
        OkGoUtils.progressRequest(MyUrl.PayVip, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 1) {
                    //0元支付
                    paySuccess();
                    return;
                }
                if (code != 0) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(body);
                    String sign = jsonObject.getString("sign");
                    if (TextUtils.isEmpty(sign)) {
                        paySuccess();
                    } else {
                        if (rgPay.getCheckedRadioButtonId() == R.id.rb_ali) {
                            //支付宝支付
                            alipay(body);
                        } else if (rgPay.getCheckedRadioButtonId() == R.id.rb_wchat) {
                            // 微信支付
                            wxPay(body);
                        } else {
                            // 佣金支付
                            paySuccess();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }
}
